using AutoMapper;
using B.S.RbacData.ErrorCode;
using B.S.RbacData.Infrastructure;
using ContentmanagementBase.Domain;
using ContentmanagementBaseWrite.API.Applications.Commands.Departments;
using MediatR;

namespace ContentmanagementBaseWrite.API.Applications.Commandhandlters.Departments
{
    /// <summary>
    /// 新增科室命令处理
    /// </summary>
    public class AddNewDepartmentCommandHandler : IRequestHandler<AddNewDepartmentCommand, ApiResult<int>>
    {
        /// <summary>
        /// 科室仓储
        /// </summary>
        private readonly IBaseRepository<DepartmentManagementModel> _departmentRepository;
        /// <summary>
        /// 映射器
        /// </summary>
        private readonly IMapper mapper;
        /// <summary>
        /// 日志记录器
        /// </summary>
        private readonly ILogger<AddNewDepartmentCommandHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="departmentRepository">科室仓储</param>
        /// <param name="mapper">映射器</param>
        /// <param name="logger">日志记录器</param>
        public AddNewDepartmentCommandHandler(IBaseRepository<DepartmentManagementModel> departmentRepository, IMapper mapper, ILogger<AddNewDepartmentCommandHandler> logger)
        {
            _departmentRepository = departmentRepository;
            this.mapper = mapper;
            _logger = logger;
        }

        /// <summary>
        /// 处理新增科室命令
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns></returns>
        public async Task<ApiResult<int>> Handle(AddNewDepartmentCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 验证科室名称是否已存在
                var existingDepartments = _departmentRepository.GetAll().Where(x => x.DepartmentName == request.DepartmentName);
                // 如果已存在，返回错误
                if (existingDepartments.Any())
                {
                    return new ApiResult<int>
                    {
                        code = ResultEnumCode.error,
                        message = "科室名称已存在！",
                        data = 0
                    };
                }


                _logger.LogInformation("开始处理科室新增命令，科室名称：{DepartmentName}", request.DepartmentName);

                // 创建科室实体
                var departmentEntity = mapper.Map<DepartmentManagementModel>(request);
                // 设置等级
                if (request.ParentId > 0)
                {
                    departmentEntity.DepartmentGrade=2;
                }
                departmentEntity.CreatedTime = DateTime.Now;
                departmentEntity.UpdatedTime = DateTime.Now;
                departmentEntity.CreatedBy = 1;
                departmentEntity.UpdatedBy = 0;

                _logger.LogDebug("科室实体映射完成，实体信息：{@Entity}", departmentEntity);

                // 保存到数据库
                _logger.LogInformation("开始保存科室到数据库");
                var result = await _departmentRepository.AddAsync(departmentEntity);
                _logger.LogInformation("数据库保存完成，影响行数：{Result}", result);

                if (result > 0)
                {
                    _logger.LogInformation("科室新增成功，ID：{Id}", departmentEntity.Id);
                    return new ApiResult<int>
                    {
                        code = ResultEnumCode.Ok,
                        message = "科室新增成功",
                        data = departmentEntity.Id
                    };
                }
                else
                {
                    _logger.LogWarning("科室新增失败，数据库未返回影响行数");
                    return new ApiResult<int>
                    {
                        code = ResultEnumCode.fails,
                        message = "科室新增失败",
                        data = 0
                    };
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "科室新增过程中发生异常，科室名称：{DepartmentName}", request.DepartmentName);
                return new ApiResult<int>
                {
                    code = ResultEnumCode.fails,
                    message = $"科室新增异常：{ex.Message}",
                    data = 0
                };
            }
        }
    }
}